<template>   
  <!-- 首頁組件的擺放 -->
  <div class="layout-container">
    <!-- 顶部标题栏 -->
    <header v-if="!isChatWindow && !isDelegationDetail" class="header" :class="{ 'blurred': isMenuOpen }">       
      <div class="header-left">         
        <img :src="userAvatar" class="avatar" @click.stop="toggleSideMenu" />
        <span class="username" v-if="userName">{{ userName }}</span>         
      </div>     
      
      <div class="header-center">
        <h1 class="title">{{ pageTitle }}</h1>
      </div>
      
      <div class="header-right">         
        <!-- 只在委托列表页面显示筛选器 -->
        <a v-if="currentRoute === 'DelegationList'" class="menu-link" @click="toggleSelectMenu">
          <img src="../assets/icons/list.svg" alt="筛选" class="menu-icon" />
        </a>      
      </div>     
    </header>

    <!-- 信息還是委托界面 -->
    <main class="main-content" :class="{ 'blurred': isMenuOpen }" @click.stop="handleMainClick">       
      <component :is="currentComponent" :disabled="isMenuOpen" />   
    </main>     


    <!-- 底部導航欄 -->
    <nav class="bottom-nav" 
         v-if="!isChatWindow && !isDelegationDetail" 
         :class="{ 'disabled': isMenuOpen }" >
      <a class="nav-link left-link" 
         @click="navigateTo('DelegationList')"
         :class="{ 'active': currentRoute === 'DelegationList' }">
        <img  src="../assets/icons/delegation.svg"  class="img1"
             alt="列表" />
      </a>
      
      <a class="publish-link" @click="navigateTo('Publish')">
        <img src="../assets/icons/pen.svg" alt="发布" class="publish-icon" />
      </a>
      
      <a class="nav-link right-link" 
         @click="navigateTo('ChatList')" 
         :class="{ 'active': currentRoute === 'ChatList' }"> 
        <img src="../assets/icons/message.svg" class="img2"
             alt="消息" />
        
      </a>
    </nav>

    <!-- 添加遮罩层 当侧边菜单打开时，点击即可关闭侧边菜单 -->
    <div 
      v-if="isMenuOpen" 
      class="overlay"
      @click="closeSideMenu"
    ></div>

    <!-- 引入侧边菜单 -->
    <Transition name="slide">       
      <SideMenu v-if="isMenuOpen" />     
    </Transition>     
  </div> 
</template>  

<script setup>
// 导入所需的 Vue API
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import SideMenu from '../views/SideMenu.vue'
import DelegationList from '../views/DelegationList.vue'
import ChatList from '../views/ChatList.vue' 
import ChatWindow from '../views/ChatWindow.vue'
import logoSvg from '../assets/logo.svg'
import userSvg from '../assets/1.svg'

const isMenuOpen = ref(false)
const router = useRouter()
const route = useRoute()
const currentRoute = ref(route.name)

// 修改这部分代码
const currentUser = ref(null)
try {
  const userStr = localStorage.getItem('user')
  currentUser.value = userStr ? JSON.parse(userStr) : null
} catch (error) {
  console.error('解析用户数据失败:', error)
  currentUser.value = null
}

const userInfo = ref(null)

// 修改获取用户信息的方法
const fetchUserInfo = async () => {
  try {
    // 从localStorage获取用户信息
    const userStr = localStorage.getItem('user')
    if (!userStr) {
      console.log('未找到用户信息')
      return
    }

    const userData = JSON.parse(userStr)
    const userId = userData?.uid

    if (!userId) {
      console.error('未找到用户ID')
      return
    }



  } catch (error) {
    console.error('获取用户信息失败:', error)
    userInfo.value = null
  }
}

const isChatWindow = computed(() => currentRoute.value === 'ChatWindow')
const isDelegationDetail = computed(() => currentRoute.value === 'DelegationDetail')

// 根据路由名称计算当前应该显示的组件
const currentComponent = computed(() => {
  return route.matched[route.matched.length - 1]?.components?.default || DelegationList
})

// 根据路由名称计算页面标题
const pageTitle = computed(() => {
  switch (currentRoute.value) {
    case 'ChatList':  // 修改这行，原为 MessageList
      return '消息'
    case 'DelegationList':
      return '委托列表'
    case 'ChatWindow':
      return '聊天' // 或者根据聊天对象动态设置标题
    default:
      return '委托列表'
  }
})

// 定义一个检查用户认证状态的函数
const checkUserAuth = () => {
  const userStr = localStorage.getItem('user')
  if (!userStr) {
    router.push('/login')
    return false
  }
  return true
}

// 修改用户头像计算属性
const userAvatar = computed(() => {
  if (!userInfo.value) return logoSvg
  return userInfo.value.avatar || userSvg // 使用后端返回的头像URL，如果没有则使用默认头像
})

// 添加用户名称计算属性
const userName = computed(() => {
  if (!userInfo.value) return ''
  return userInfo.value.username || ''
})

// 修改getCurrentUser方法
const getCurrentUser = async () => {
  await fetchUserInfo()
}

const toggleSideMenu = () => {
  const isAuthenticated = localStorage.getItem('user')
  //如果用户未认证则转到登录？
  if (!isAuthenticated) {
    router.push('/login')
    return
  }
  isMenuOpen.value = !isMenuOpen.value
}

// 修改关闭侧边栏的方法
const closeSideMenu = () => {
  isMenuOpen.value = false
}

const handleMainClick = (event) => {
  if (isMenuOpen.value) {
    event.stopPropagation()
    event.preventDefault()
  }
}

const toggleSelectMenu = () => {
  if (!checkUserAuth()) return
  router.push({ name: 'Select' })
}

const navigateTo = (routeName) => {
  if (!checkUserAuth()) return
  currentRoute.value = routeName
  router.push({ name: routeName })
}

// 修改onMounted钩子，移除定期检查
onMounted(async () => {
  await fetchUserInfo()
})

// 在路由导航守卫中添加检查
watch(
  () => route.name,
  (newName) => {
    currentRoute.value = newName
  }
)

// 在组件挂载时获取用户信息
onMounted(async () => {
  await fetchUserInfo()
})

//用于处理多标签页的数据同步，用于处理组件级别的状态管理
// 监听 localStorage 变化
window.addEventListener('storage', getCurrentUser)

// 在组件卸载时移除监听器
onUnmounted(() => {
  window.removeEventListener('storage', getCurrentUser)
})

// 监听路由变化
watch(
  () => route.name,
  (newName) => {
    currentRoute.value = newName
  }
)
</script>

<style scoped>
/* 添加模糊动画样式 */
@keyframes blurIn {
  from {
    filter: blur(0);
  }
  to {
    filter: blur(20px);
  }
}


.layout-container {
  height: 100vh;
  position: relative;
  display: flex;
  flex-direction: column;
  width: 100%;
  margin: 0 auto;
  max-width: 1024px; /* 添加全局最大宽度限制 */
}

/* 小型手机设备 (320px - 480px) */
@media screen and (min-width: 320px) and (max-width: 480px) {
  .layout-container {
    width: 100%;
    max-width: none;
  }
}

/* 中型手机设备 (481px - 767px) */
@media screen and (min-width: 481px) and (max-width: 767px) {
  .layout-container {
    width: 100%;
    max-width: none;
  }
}

/* 平板设备 (768px - 1024px) */
@media screen and (min-width: 768px) {
  .layout-container {
    width: 100%;
    max-width: 768px;
  }
}

.header {
  display: grid;
  grid-template-columns: 1fr auto 1fr; /* 三等分布局 */
  align-items: center;
  padding: 0px 20px;
  margin: 3px 0;
  background: white;
  height: 62px;
  box-sizing: border-box;
}

.header.blurred {
  animation: blurIn 0.3s ease forwards;
  /* filter: blur(20px); */
}

.header-left {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  height: 62px;
  gap: 10px; /* 添加间距 */
}

.username {
  font-size: 14px;
  color: #333;
  margin-left: 5px;
}

.header-center {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 62px;
}

.header-right {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  height: 62px;
}

.avatar {
  width: 42px;
  height: 42px;
  border-radius: 50%;
  cursor: pointer;
}

.title {
  font-family: SourceHanFontBold;
  font-size: 1.2rem;
  font-weight: 500;
  color: black;
  margin: 0;
  white-space: nowrap;
}



.menu-link {
  padding: 5px;
  /* 手动对齐 */
  padding-top: 10px;
  cursor: pointer;
  transition: transform 0.2s;
}

.menu-link:active {
  transform: scale(0.95);
}

.menu-icon {
  width: 24px;
  height: 24px;

  vertical-align: middle;
  
}

.main-content {
  flex: 1;
  overflow-y: auto;

  width: 100%;
  max-width: 100%;
  margin: 0 auto;
  /* padding-bottom: 94px; 与底部导航栏高度保持一致 */
  box-sizing: border-box; /* 确保padding不会增加总高度 */
  /* padding-bottom: 80px; */
}

.main-content.blurred {
  animation: blurIn 0.3s ease forwards;
  /* filter: blur(20px); */
  pointer-events: none;
}

.bottom-nav {
  display: flex;
  bottom: 0;
  left: 0;
  right: 0;
  justify-content: space-around;
  /* align-items: center; */
  background: linear-gradient(to top, rgba(255, 255, 255, 0.6), rgba(255, 255, 255, 0.3));
  backdrop-filter: blur(40px); /* 毛玻璃效果 */
  -webkit-backdrop-filter: blur(40px); /* Safari 兼容 */
  border-top: 1px solid rgba(238, 238, 238, 0.5);
  padding: 8px 0;
  height: 94px;
  max-width: inherit;
  /* new */
  position: fixed; /* 改为固定定位 */
  width: 100%;
  margin: 0 auto;
  z-index: 10;
}


.bottom-nav.disabled {
  animation: blurIn 0.3s ease forwards;
  /* filter: blur(20px); */
  pointer-events: none;
  opacity: 0.7;
}

.nav-link {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center; /* 上下居中 */
  text-decoration: none;
  color: #777777;
  font-size: 12px;
  gap: 4px;
  transition: all 0.2s;
  position: relative;
  padding: 0px;
  -webkit-tap-highlight-color: transparent; /* 移除点击高亮 */
  user-select: none; /* 防止文本被选中 */
  padding-bottom: 40px;

}

.left-link {
  margin-left: 40px;
}

.right-link {
  margin-right: 40px;
}


/* 移除点击反馈效果相关的样式 */
.nav-link::after {
  display: none; /* 移除原来的点击效果 */
}

.nav-link:active {
  transform: scale(0.95); /* 保留缩放动画 */
}

/* 两个图标分别编辑尺寸 */
.nav-link .img1 {
  width: 27px;
  height: 29px;
  transition: transform 0.2s;

}

.nav-link .img2 {
  width: 33px;
  height: 29px;
  transition: transform 0.2s;

}

/* 修改导航图标的默认颜色 */
.nav-link img {
  width: 24px;
  height: 24px;
  transition: transform 0.2s;
  filter: invert(57%) sepia(2%) saturate(1%) hue-rotate(48deg) brightness(90%) contrast(86%); /* 生成 #8f9191 颜色 */
}

/* 激活状态保持蓝色 */
.nav-link.active img {
  transform: scale(1.1);
  filter: invert(71%) sepia(19%) saturate(544%) hue-rotate(178deg) brightness(94%) contrast(90%); /* 生成 #9dbce3 颜色 */
}

/* 修改发布按钮容器样式 */
.publish-link {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 56px;
  height: 56px;
  margin-top: -30px;
  background: #9dbce3;
  border-radius: 30%;
  box-shadow: 0 2px 8px rgba(157, 188, 227, 0.5);
  transition: all 0.2s ease; /* 修改过渡效果 */
  -webkit-tap-highlight-color: transparent;
}

/* 修改发布按钮图标样式 */
.publish-icon {
  width: 32px;
  height: 32px;
  filter: brightness(0) invert(1);
  transition: all 0.2s ease; /* 与容器使用相同的过渡效果 */
  transform-origin: center; /* 确保从中心缩放 */
}

.publish-link:active {
  transform: scale(0.95);
  box-shadow: 0 1px 4px rgba(157, 188, 227, 0.5);
}

/* 移除单独的图标动画 */
.publish-link:active .publish-icon {
  transform: none; /* 移除图标的独立缩放 */
}

.slide-enter-active,
.slide-leave-active {
  transition: transform 0.3s ease;
}

/* 添加遮罩层样式 */
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 10;
}

/* 确保侧边栏在遮罩层之上 */
.slide-enter-active,
.slide-leave-active {
  z-index: 11;
}

.slide-enter-from,
.slide-leave-to {
  transform: translateX(-100%);
}

.user-info {
  margin-right: 1rem;
  font-size: 0.9rem;
  color: #666;
}
</style>